package com.tpo.jnotes.client.layer.binding;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map.Entry;

import com.tpo.jnotes.client.lib.interfaces.IModel;
import com.tpo.jnotes.client.lib.interfaces.IModelEntity;
import com.tpo.jnotes.client.lib.interfaces.IViewEntity;
import com.tpo.jnotes.client.lib.util.BeansUtils;
import com.tpo.jnotes.client.main.Logging;

public class Binding
{

    private static IModel model;

    public static void setModel( IModel model )
    {
        Binding.model = model;
    }

    public static void bind( IViewEntity viewEntity )
    {
        viewEntity.getComponent().addPropertyChangeListener( new PropertyChangeListener()
        {

            @Override
            public void propertyChange( PropertyChangeEvent evt )
            {
                try
                {
                    BindingsEnum.valueOf( evt.getPropertyName() );
                }
                catch( IllegalArgumentException e )
                {
                    return;
                }

                IViewEntity viewEntity = (IViewEntity)evt.getSource();
                String propertyName = evt.getPropertyName();
                Object propertyValue = evt.getNewValue();
                if( !BeansUtils.getBeanProperty( viewEntity, propertyName ).equals( propertyValue ) )
                {
                    Logging.trace( "Binding > property changed. " + propertyName + " = " + propertyValue );
                    model.setProperty( viewEntity.getId(), propertyName, propertyValue );
                    model.update();
                }
            }
        } );

        HashMap< String, String > bindings = viewEntity.getBindings();
        IModelEntity modelEntity = model.getEntity( viewEntity.getId() );
        for( Entry< String, String > entry : bindings.entrySet() )
        {
            try
            {
                Logging.trace( "Binding > property set. " + entry.getKey() + " = " + entry.getValue() );
                BeansUtils.setProperty( viewEntity, entry.getKey(),
                    modelEntity.getProperty( entry.getValue() ) );
                // beanWrp.setPropertyValue(entry.getKey(), modelEntity.getProperty(entry.getValue()));
            }
            catch( Exception e )
            {
                Logging.fatal( "Binding > property " + entry.getKey()
                    + " not found, check ViewEntity, there should be a setter for each Bindings enum." );
                Logging.fatal( e );
            }
        }
    }
}
